package com.piece.core.framework.util.file;

import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.GZIPInputStream;

/**
 * .tar,.gz文件工具类
 */
public class TarFileUtil {

    /**
     * 解压.tar文件
     */
    public static void unTarFile(File srcFile, String destPath) throws Exception {
        TarArchiveInputStream tar = null;
        try {
            tar = new TarArchiveInputStream(new FileInputStream(srcFile));
            deArchive(new File(destPath), tar);
        } catch (Exception e) {
            tar.close();
        }
    }

    /**
     * 解压.tar文件
     */
    private static void deArchive(File destFile, TarArchiveInputStream tar) throws Exception {
        TarArchiveEntry entry;
        while (null != (entry = tar.getNextTarEntry())) {
            // 文件
            String dir = destFile.getPath() + File.separator + entry.getName();
            File dirFile = new File(dir);
            // 文件检查
            mkParentDir(dirFile);
            if (entry.isDirectory()) {
                dirFile.mkdirs();
            } else {
                deArchiveFile(dirFile, tar);
            }
        }
    }

    /**
     * 解压.tar文件
     */
    private static void deArchiveFile(File destFile, TarArchiveInputStream tar) throws Exception {
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile));
        int count;
        byte data[] = new byte[1024];
        while ((count = tar.read(data, 0, 1024)) != -1) {
            bos.write(data, 0, count);
        }
        bos.close();
    }

    /**
     * 解压tar.gz
     */
    public static void unTarGzFile(File gzFile, String descDir) throws Exception {
        GZIPInputStream inputStream = new GZIPInputStream((new FileInputStream(gzFile)));
        TarArchiveInputStream tarArchiveInputStream = new TarArchiveInputStream(inputStream);
        deArchive(new File(descDir), tarArchiveInputStream);
    }

    /**
     * 递归创建上级目录
     */
    public static void mkParentDir(File dirFile) {
        File parentFile = dirFile.getParentFile();
        if (!parentFile.exists()) {
            mkParentDir(parentFile);
            parentFile.mkdirs();
        }
    }
}
